<?php
// 库1
$dsn1 = "mysql:host=reportdbt-0.reportdbt.test.svc.test.yafex.net;dbname=yafex-statistics";
// 库2
$dsn2 = "mysql:host=statisticdbt-0.statisticdbt.test.svc.test.yafex.net;dbname=yafex-statistics-business";
// 用户名
$user = "apptest";
$pwd1 = "Q9jzeW4Ogh";
$pwd2 = "CtJp1USwIk";
// 实例化pdo
$listing = new PDO($dsn1, $user, $pwd1);
// 实例化pdo
$task = new PDO($dsn2, $user, $pwd2);
// 事务id
$_p = uniqid("");
// 参与者准备标识
$_l = false;
// 参与者准备标识
$_t = false;
// 事务ACTIVE
$listing->query("XA START '{$_p}'");
$task->query("XA START '{$_p}'");
try {
   $sql = "insert into `test_name` (name) values('erge');";
   $result = $listing->query($sql);
   // 事务IDLE
   var_dump($listing->query("XA END '{$_p}'"));
   if ($result === false) {
      echo 'listing插入失败' . PHP_EOL;
   } elseif ($result->rowCount() > 0) {
      // 事务PREPARE
      var_dump($listing->query("XA PREPARE '{$_p}'"));
      $_l = true;
   }
   if ($_l) {
      // $sql = "update `test_age` set age = 18 where id = 1;";
      $sql = "insert `test_age` (age) values(18);";
      $result = $task->query($sql);
      // 事务IDLE
      var_dump($task->query("XA END '{$_p}'"));
      if ($result === false) {
         echo 'task更新失败' . PHP_EOL;
      } elseif ($result->rowCount() > 0) {
         // 事务PREPARE
         var_dump($task->query("XA PREPARE '{$_p}'"));
         $_t = true;
      }
   }
   if ($_l && $_t) {
      // 事务提交
      $listing->query("XA COMMIT '{$_p}'");
      $task->query("XA COMMIT '{$_p}'");
   } else {
      // 事务回滚
      $listing->query("XA ROLLBACK '{$_p}'");
      $task->query("XA ROLLBACK '{$_p}'");
   }
} catch (Exception $e) {
   $listing->query("XA ROLLBACK '{$_p}'");
   $task->query("XA ROLLBACK '{$_p}'");
   var_dump($e->getMessage());
}
